<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import TnButton from '@tuniao/tnui-vue3-uniapp/components/button/src/button.vue'
import TnPopup from '@tuniao/tnui-vue3-uniapp/components/popup/src/popup.vue'
import TnInput from '@tuniao/tnui-vue3-uniapp/components/input/src/input.vue'
import TnCheckbox from '@tuniao/tnui-vue3-uniapp/components/checkbox/src/checkbox.vue'
import { tnNavPage } from '@tuniao/tnui-vue3-uniapp/utils'
import type { NavbarRectInfo } from '@tuniao/tnui-vue3-uniapp/components/navbar'
import PageContainer from '@/components/page-container/index.vue'
import account from '@/api/account.js'
import { FILE_URL, SYSTEM_CONFIG, USER_INFO, USER_TOKEN } from '@/api/config'
const state = reactive({
  loading: false,
  loginText: '登录/注册',
  mobile: '',
  code: '',
  agent: false,
  bindPhonePopup: false,
  logo: '',
  userAgreement: '',
  privacyPolicy: '',
})
// 导航栏的高度
const navbarHeight = ref(0)
// 导航栏初始化完毕
const navbarInitFinishHandle = (info: NavbarRectInfo) => {
  navbarHeight.value = info.height
}

const clickLogin = () => {
  uni.showToast({
    title: '暂时仅支持微信小程序登录！',
    duration: 3000,
    icon: 'none',
  })
  return
  if (state.agent == false) {
    uni.showToast({
      title: '请勾选同意《用户协议》与《隐私政策》后登录',
      duration: 3000,
      icon: 'none',
    })
    return
  }
}

// 快捷登录/注册
const miniProgramLogin = () => {
  if (state.agent == false) {
    uni.showToast({
      title: '请勾选同意《用户协议》与《隐私政策》后登录',
      duration: 3000,
      icon: 'none',
    })
    return
  }

  state.loading = true
  state.loginText = '登录中···'
  uni.login({
    provider: 'weixin',
    success: async (loginRes) => {
      console.log(loginRes)
      if (loginRes.errMsg == 'login:ok') {
        account
          .miniProgramLogin({
            code: loginRes.code,
          })
          .then((result) => {
            state.loading = false
            console.log(result, 'result')
            if (result.code == 1) {
              uni.setStorageSync(USER_INFO, result.data.userInfo)
              uni.setStorageSync(USER_TOKEN, result.data.userToken)
              if (result.data.userInfo.mobile == '') {
                state.bindPhonePopup = true
                return
              } else {
                uni.reLaunch({
                  url: '/pages/index/index',
                })
              }
            } else {
              uni.showToast({
                title: result.msg,
                duration: 2000,
                icon: 'none',
              })
            }
          })
          .catch((err) => {
            console.log(err, '微信授权登录')
            uni.showToast({
              title: err,
              duration: 2000,
              icon: 'error',
            })
          })
      } else {
        uni.showToast({
          title: '请稍后重试',
          duration: 2000,
          icon: 'error',
        })
      }
    },
  })
}

const miniProgramGetphonenumber = (e: {
  detail: { errMsg: string; code: any }
}) => {
  console.log(e, 'getPhoneNumber')
  state.bindPhonePopup = true
  if (e.detail.errMsg == 'getPhoneNumber:ok') {
    account
      .miniProgramBindPhone({
        code: e.detail.code,
      })
      .then((result) => {
        console.log(result, 'result')
        uni.showToast({
          title: result.msg,
          duration: 2000,
          icon: 'none',
        })
        if (result.code == 1) {
          uni.setStorageSync(USER_INFO, result.data.userInfo)
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/index/index',
            })
          }, 2000)
        }
      })
      .catch((err) => {
        console.log(err, '微信授权获取手机号')
        uni.showToast({
          title: err,
          duration: 2000,
          icon: 'error',
        })
      })
  } else {
    uni.showToast({
      title: '手机号授权失败～',
      duration: 2000,
      icon: 'error',
    })
  }
}

onLoad((options) => {
  const systemConfig = uni.getStorageSync(SYSTEM_CONFIG)
  state.logo = systemConfig.basic.app_logo
  state.userAgreement = systemConfig.agreement.user_agreement
  state.privacyPolicy = systemConfig.agreement.privacy_policy
})
</script>

<template>
  <PageContainer :placeholder-bottom="true">
    <TnNavbar fixed :bottom-shadow="false" :placeholder="false" bg-color="rgba(255, 255, 255, 0)"
      @init-finish="navbarInitFinishHandle" />

    <view class="login">
      <!-- 顶部背景图片-->
      <view class="login__bg login__bg--top">
        <image class="bg" src="@/static/images/login-top.png" mode="widthFix" />
      </view>

      <view class="login__wrapper">
        <view class="tn-ml tn-mr tn-text-bold" style="font-size: 60rpx">
          欢迎回来
        </view>
        <view class="tn-m tn-text-lg" style="color: #aaaaaa">
          随时随地，发现新鲜事
        </view>

        <!-- 输入框内容-->
        <view class="login__info">
          <!-- #ifdef MP-WEIXIN -->
          <view class="logo">
            <image class="" :src="FILE_URL + state.logo" mode="widthFix" />
          </view>
          <!-- #endif -->
          <!-- 登录 -->
          <!-- #ifdef APP-PLUS || H5 || APP-PLUS-NVUE -->
          <view class="login__info__item">
            <TnInput v-model="state.mobile" type="number" placeholder="请输入手机号码" :custom-style="{
              borderRadius: '39rpx',
            }">
              <template #prefix> +86 </template>
            </TnInput>
          </view>

          <view class="login__info__item">
            <TnInput v-model="state.code" type="number" placeholder="请输入验证码" :custom-style="{
              borderRadius: '39rpx',
            }">
              <template #suffix>
                <TnButton text size="sm" font-size="28">获取验证码</TnButton>
              </template>
            </TnInput>
          </view>

          <TnButton width="100%" height="77rpx" text-color="#ffffff" shape="round" size="xl" font-size="30"
            :custom-style="{
              marginTop: '80rpx',
              lineHeight: '77rpx',
              letterSpacing: '0.5em',
              borderRadius: '39rpx',
              boxShadow: '1rpx 10rpx 24rpx 0rpx rgba(60, 129, 254, 0.35)',
            }" @click="clickLogin">登陆
          </TnButton>
          <!-- #endif -->
          <!-- #ifdef MP-WEIXIN -->
          <TnButton width="100%" height="77rpx" text-color="#ffffff" shape="round" size="xl" font-size="30"
            :loading="state.loading" :debounce="true" :custom-style="{
              marginTop: '80rpx',
              lineHeight: '77rpx',
              letterSpacing: '0.5em',
              borderRadius: '39rpx',
              boxShadow: '1rpx 10rpx 24rpx 0rpx rgba(60, 129, 254, 0.35)',
            }" @click="miniProgramLogin">
            {{ state.loginText }}
          </TnButton>
          <!-- #endif -->
          <view class="tn-mt-xl tn-flex tn-flex-row items-center">
            <TnCheckbox v-model="state.agent" />
            <p class="tn-ml-xs">我已阅读并同意</p>
            <TnButton text @click="tnNavPage(state.userAgreement)">用户协议</TnButton>和
            <TnButton text @click="tnNavPage(state.privacyPolicy)">隐私政策</TnButton>
          </view>
        </view>
      </view>

      <!-- 底部背景图片-->
      <view class="login__bg login__bg--bottom">
        <image src="@/static/images/login-bottom.png" mode="widthFix" />
      </view>
    </view>

    <TnPopup v-model="state.bindPhonePopup" open-direction="bottom" radius="30" :safe-area-inset-bottom="false">
      <view class="popup-box">
        <view class="title"> 绑定手机号</view>
        <view class="content">
          亲爱的用户，感谢您信任并使用本小程序！为了确保您的账户安全并享受更全面的社区服务，我们需要在您使用微信登录后，绑定一个手机号码。立即绑定手机号，开启您的社区之旅吧！
        </view>
        <view class="agree-btn-container">
          <TnButton width="90%" height="80" shape="round" open-type="getPhoneNumber"
            @getphonenumber="miniProgramGetphonenumber">
            一 键 快 捷 绑 定
          </TnButton>
        </view>
      </view>
    </TnPopup>
  </PageContainer>
</template>

<style lang="scss" scoped>
@use '@/static/css/login.scss';
</style>
